package cn.sc.summer.redis.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.sc.summer.constant.gateway.GatewayConstant;
import cn.sc.summer.constant.project.ProjectConstant;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名：网关路由获取工具类
 *
 * @author a-xin
 * @date 2024/7/1 11:37
 */
public class RouteUtil {

    /**
     * 获取该服务的真实全路径信息
     *
     * @param serverName 服务名称
     * @param path       路径
     * @return 全路径信息
     */
    public static String getRawPath(String serverName, String path) {
        String route = (String) RedisHelper.hGet(GatewayConstant.ROUTING_PREFIX, serverName);
        if (CharSequenceUtil.isBlank(route)) {
            throw new RuntimeException("Please start the gateway service first!");
        }
        return route.replace("/**", path);
    }

    /**
     * 获取该服务的真实全路径信息
     *
     * @param path 路径
     * @return 全路径信息
     */
    public static String getRawPath(String path) {
        String route = (String) RedisHelper.hGet(GatewayConstant.ROUTING_PREFIX, ProjectConstant.SERVER_NAME);
        if (CharSequenceUtil.isBlank(route)) {
            throw new RuntimeException("Please start the gateway service first!");
        }
        return route.replace("/**", path);
    }

    /**
     * 获取该服务的真实全路径信息
     *
     * @param serverName 服务名称
     * @param request    请求体
     * @return 全路径信息
     */
    public static String getRawPath(String serverName, HttpServletRequest request) {
        String route = (String) RedisHelper.hGet(GatewayConstant.ROUTING_PREFIX, serverName);
        if (CharSequenceUtil.isBlank(route)) {
            throw new RuntimeException("Please start the gateway service first!");
        }
        String requestURI = request.getRequestURI();
        return route.replace("/**", requestURI);
    }

    /**
     * 获取该服务的真实全路径信息
     *
     * @param request 请求体
     * @return 全路径信息
     */
    public static String getRawPath(HttpServletRequest request) {
        String route = (String) RedisHelper.hGet(GatewayConstant.ROUTING_PREFIX, ProjectConstant.SERVER_NAME);
        if (CharSequenceUtil.isBlank(route)) {
            throw new RuntimeException("Please start the gateway service first!");
        }

        String requestURI = request.getRequestURI();
        return route.replace("/**", requestURI);
    }

    /**
     * 获取当前所有路由信息
     *
     * @return 路由map
     */
    public static Map<String, String> getRouteMap() {
        Map<Object, Object> routingMap = RedisHelper.hmGet(GatewayConstant.SWAGGER_DYNAMIC_ROUTING);
        Map<String, String> definitionMap = new HashMap<>();
        if (CollUtil.isNotEmpty(routingMap)) {
            routingMap.forEach((key, value) -> definitionMap.put(key.toString(), value.toString()));
        }
        return definitionMap;
    }

}
